function [ MF,corrs,MFN,corrsN, ks,height,width, FFORMATTED,IMS,corrsFormatted] = generateFImages( seqname,noiselevel, numCorruptFs,override )

% a lot of the things here are taken from peter kovesi
%http://www.csse.uwa.edu.au/~pk/research/matlabfns/Robust/example/index.htm
%l
if(nargin<4)
    override=0;
end

matchprefixname={'correlation','sift'};
matchtech=2; % 1 for haris with correlation, 2 for sift
w = 11;    % Window size for correlation matching
flagrecreate=0;
t = .001;  % Distance threshold for deciding outliers
showgraphs=0;
countF=0;
limit=7; % if this limit is set to a number higher than zero, then only that many frames are read, otherwise the whole sequence
fthreshold=2;
%setting override to 1 will reset all features

nonlinrefine = 0; % to nonlinear refine it





[IMFiles , realFold , savedfeaturesfolder , IMSDESCNAMES,IMS ]=writeImageFeatures( seqname,matchtech,limit,override );

ks=findExistingIntrinsics(realFold,seqname);




numimages=size(IMFiles,1);

if(limit>0 && numimages>limit)
    numimages=limit;
end


FFORMATTED=cell(numimages);
corrsFormatted=cell(numimages,numimages);

[height,width,~]=size(IMS{1,1});
dmax = width/2;

infofile=[savedfeaturesfolder  '/matching' seqname '_' matchprefixname{matchtech} '_old.txt'];
infofilefinal=[savedfeaturesfolder  '/matching' seqname '_' matchprefixname{matchtech} '.txt'];
fidstat = fopen(infofile,'w');
fprintf(fidstat,'Fundamental matrix , left images , right image , inliers ,  total  , mean inliers, median inliers , max \n');


for i=1:numimages
    for j=1:i
        if(i~=j)
            
            matchfilename=[savedfeaturesfolder  '/matches_' seqname '_' matchprefixname{matchtech} '_' num2str(i) '_' num2str(j) '.mat'];
            fundfilename=[savedfeaturesfolder  '/fundMatrix_' seqname '_' matchprefixname{matchtech} '_' num2str(i) '_' num2str(j) '.mat'];
            fundfilenametext=[savedfeaturesfolder  '/fundMatrix_' seqname '_' matchprefixname{matchtech} '_' num2str(i) '_' num2str(j) '.txt'];
            imagedirty=[savedfeaturesfolder  '/matches_dirty_' seqname '_' matchprefixname{matchtech} '_' num2str(i) '_' num2str(j) '.jpg'];
            imageclean=[savedfeaturesfolder  '/matches_clean_' seqname '_' matchprefixname{matchtech} '_' num2str(i) '_' num2str(j) '.jpg'];
            countF=countF+1;
            disp(['sequence: ' seqname ' fundamental matrix number ' num2str(countF) ' between frame ' num2str(i) ' with ' num2str(j)]);
            
            [vm1,vn1,vj1]=size(IMS{1,i});
            [vm2,vn2,vj2]=size(IMS{1,j});
            
            
            if(vj1>1 )
                im1 =   rgb2gray(IMS{1,i});
            else
                im1 =   (IMS{1,i});
            end
            if(vj2>1 )
                im2 =   rgb2gray(IMS{1,j});
            else
                im2 =   (IMS{1,j});
            end
            
            if(matchtech==1)
                
                
                
                if(exist(IMSDESCNAMES{1,i},'file')~=0)
                    load(IMSDESCNAMES{1,i},'cimfile','rfile','cfile');
                    cim1=cimfile ;r1=rfile ;c1= cfile;
                else
                    error(' descriptor not found');
                end
                
                if(exist(IMSDESCNAMES{1,j},'file')~=0)
                    load(IMSDESCNAMES{1,j},'cimfile','rfile','cfile');
                    cim2=cimfile ;r2=rfile ;c2= cfile;
                    
                else
                    error(' descriptor not found');
                end
                
                if(exist(matchfilename ,'file')~=0)
                    load(matchfilename,'m1','m2');
                else
                    [m1,m2] = matchbycorrelation(im1, [r1';c1'], im2, [r2';c2'], w, dmax);
                    save(matchfilename,'m1','m2');
                    flagrecreate=1;
                end
                
                
                x1 = [m1(2,:); m1(1,:); ones(1,length(m1))];
                x2 = [m2(2,:); m2(1,:); ones(1,length(m1))];
            else
                
                if(exist(IMSDESCNAMES{1,i},'file')~=0)
                    load(IMSDESCNAMES{1,i},'frames','descriptors');
                    frames1=frames;descriptors1=descriptors;
                else
                    error(' descriptor not found');
                end
                
                if(exist(IMSDESCNAMES{1,j},'file')~=0)
                    load(IMSDESCNAMES{1,j},'frames','descriptors');
                    frames2=frames;descriptors2=descriptors;
                else
                    error(' descriptor not found');
                end
                
                
                if(exist(matchfilename ,'file')~=0)
                    load(matchfilename,'matches');
                else
                    matches=siftmatch( descriptors1, descriptors2 ) ;
                    save(matchfilename,'matches');
                    flagrecreate=1;
                end
                
                
                [sm,sn]=size(matches);
                disp(['sequence: ' seqname  'number of matches was: ' num2str(sn)]);
                
                x1=zeros(3,sn);
                x2=zeros(3,sn);
                
                
                
                for p=1:sn
                    x1(1,p)= frames1(1,matches(1,p)) ;
                    x1(2,p)= frames1(2,matches(1,p)) ;
                    x1(3,p)=1  ;
                    m1(1,p)= x1(2,p) ;
                    m1(2,p)= x1(1,p) ;
                    
                    x2(1,p)=  frames2(1,matches(2,p));
                    x2(2,p)=  frames2(2,matches(2,p));
                    x2(3,p)= 1 ;
                    m2(1,p)= x2(2,p) ;
                    m2(2,p)= x2(1,p) ;
                end
                
                for p=1:sn
                    r1(p,1)= x1(2,p)  ;
                    c1(p,1)= x1(1,p)  ;
                    
                    r2(p,1)= x2(2,p)  ;
                    c2(p,1)= x2(1,p)  ;
                end
                
                
                %         plotmatches(I1,I2,frames1(1:2,:),frames2(1:2,:),matches) ;
                %         drawnow ;
            end
            
            if(countF<=numCorruptFs)
                ninliers=1:1:size(x2,2);
                FC = fundmatrix(x1(:,ninliers), x2(:,ninliers));
            else
                
                [FC, ninliers] = ransacfitfundmatrix(x1, x2, t);
                [bdc] = funddist(FC, [x1 ; x2]);
                ninliers=find(bdc<fthreshold);
                display(['number of matches is now ' num2str(size(ninliers,2)) ' inlier mean error is ' num2str(mean(bdc(ninliers))) ]);
                for g=1:2
                    FC = fundmatrix(x1(:,ninliers), x2(:,ninliers));
                    [bdc] = funddist(FC, [x1 ; x2]);
                    ninliers=find(bdc<fthreshold);
                    
                    display(['number of matches is now ' num2str(size(ninliers,2)) ' inlier mean error is ' num2str(mean(bdc(ninliers))) ]);
                end
                ninliers=find(bdc<median(bdc(ninliers)));
                FC = fundmatrix(x1(:,ninliers), x2(:,ninliers));
                  
                display(['number of matches is now ' num2str(size(ninliers,2)) ' inlier mean error is ' num2str(mean(bdc(ninliers))) ]);
                
                
                    
                    pts0=[x1(1,ninliers)' x1(2,ninliers)'];
                    pts1=[x2(1,ninliers)' x2(2,ninliers)'];
                    [FCN, ~]=fundest(pts0, pts1, 0.95, 1, 'sampson_err');
                    [bdc] = funddist(FCN, [x1 ; x2]);
                    ninliersN=find(bdc<fthreshold);
                    ninliersN=find(bdc<median(bdc(ninliersN)));
                    display(['NONLIN number of matches is now ' num2str(size(ninliersN,2)) ' inlier mean error is ' num2str(mean(bdc(ninliersN))) ]);
                
               
               
                
                
                
                
            end
            
            inliers=ninliers;
            F=FC;

            save(fundfilename,'F','inliers');
            
            
            if(size(F,2)>0)
                
                save(fundfilenametext,'F','-ascii');
                
            end
            
            
            
            FFORMATTED{i,j }=F;
            FFORMATTED{j,i }=F';
            MF{countF}=F;
               MFN{countF}=FCN;
            [im,in]=size(inliers);
            
            disp(['sequence: ' seqname 'fund matrix between frames: ' num2str(i) ' and ' num2str(j) ' has ' num2str(in) ' inliers. Fund ' num2str(countF) ' out of ' num2str((numimages*(numimages-1))/2)]);
            
            
            xin1=x1(:,inliers);
            xin2=x2(:,inliers);
            
               xin1N=x1(:,ninliersN);
            xin2N=x2(:,ninliersN);
            
            corrs{1,countF}=xin1;
            corrs{2,countF}=xin2;
            
            corrsN{1,countF}=xin1N;
            corrsN{2,countF}=xin2N;
            
            corrsFormatted{i,j}=[xin1 ; xin2]  ;
            corrsFormatted{j,i}=[xin2 ; xin1]  ;
            
            
            
            if(   flagrecreate==1)
                if(size(corrs{1,countF},2)>8)
                    [bd] = funddist(F, [corrs{1,countF} ; corrs{2,countF}]);
                end
                fprintf(fidstat,[ num2str(countF) ' , '  num2str(i)  ' , '  num2str(j)  ' , '  num2str(in)  ' , '  num2str(size(x1,2)) ' , ' num2str(mean(bd)) ' , ' num2str(median(bd)) ' , ' num2str(max(bd)) ' \n ']);
                
                figure('Visible','off'); show(im1,0), title('Putative matches'), hold on
                for n = 1:length(m1);
                    line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)])
                end
                saveas(gcf,imagedirty);
                
                % Display both images overlayed with inlying matched feature points
                figure('Visible','off');  show(double(im1)+double(im2),0), title('Inlying matches'), hold on
                plot(m1(2,inliers),m1(1,inliers),'r+');
                plot(m2(2,inliers),m2(1,inliers),'g+');
                
                for n = inliers
                    line([m1(2,n) m2(2,n)], [m1(1,n) m2(1,n)],'color',[0 0 1])
                end
                saveas(gcf, imageclean);
            end
            
            
        end
    end
    
    
    
end
fclose(fidstat);

if(flagrecreate==1)
    copyfile(infofile,infofilefinal,'f') ;
end

delete(infofile);


end

function [kvs]=findExistingIntrinsics(realFold,seqname)

CAMFiles=dir([realFold '*.camera']);
PFiles=dir([realFold '*.P']);
HMNFiles=dir([realFold '*.hmnparm']);
KFiles=dir([realFold '*.K']);
[mp,~]=size(PFiles);
[cp,~]=size(CAMFiles);
[hmn,~]=size(HMNFiles);
[kmn,~]=size(KFiles);
if(cp~=0)
    for i=1:cp
        
        cam{1,i}=importdata( [realFold CAMFiles(i,1).name]);
        kvs{1,i}=cam{1,i}(1:3,1:3);
        
    end
elseif(mp~=0)
    
    for i=1:mp
        
        P{1,i}=load( [realFold PFiles(i,1).name]);
        [kvs{1,i}, rrrrr, tttt] = vgg_KR_from_P(P{1,i});
        
    end
elseif(hmn~=0)
    K=load( [realFold HMNFiles(1,1).name]);
    kvs{1,1}=K;
    
elseif(kmn~=0)
    K=load( [realFold KFiles(1,1).name]);
    kvs{1,1}=K;
    
else
    display(['no intrinsics found for seqname ' seqname]);
    kvs{1,1}=zeros(3,3);
end




end